//#include "serialportwidget.h"
#include "netsettings.h"
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QGridLayout>
#include <QString>
#include <QTimer>
#include <QList>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <qdebug.h>
#include <qfile.h>
#include <QFile>
#include <sys/ioctl.h>
#include <unistd.h>
#include <QString>
#include <QNetworkInterface>
#include <QList>
#include <QFrame>


#include "InputMethod/inputmethod.h"

NetSettings::NetSettings(QWidget *parent) : JDialog(parent)
{

	process = new QProcess(this);
	process1 = new QProcess(this);
	process2 = new QProcess(this);
    process_mac = new QProcess(this);

	mode = new QComboBox(this);

	QList<QString>	modeList;
    modeList	<< "动态模式"
                << "静态模式";
        
	mode->addItems(modeList);
	mode->setView(new QListView());

	checkMode();
	


    im = new InputMethod;
  
    QLabel *pipLabel1 = new QLabel;
    QLabel *pSonnetLabel= new QLabel;
    QLabel *ppassnetLabel= new QLabel;
    QLabel *pDNS = new QLabel;
    QLabel *Diplabel = new QLabel;
	QLabel *maclabel = new QLabel;

	QGridLayout *pSubLayout = new QGridLayout;
	QHBoxLayout *butly = new QHBoxLayout;

    QPushButton *pSaveButton= new QPushButton(this);
    QPushButton *prefreshButton= new QPushButton(this);
    QPushButton *recoverButton = new QPushButton(this);


    qlineedit_ip = new QLineEdit(this);
    qlineedit_mask = new QLineEdit(this);
    qlineedit_gw = new QLineEdit(this);
    qlineedit_dns = new QLineEdit(this);
	qlineedit_mac = new QLineEdit(this);

	qlineedit_ip->setEnabled(false);
	qlineedit_gw->setEnabled(false);
	qlineedit_mask->setEnabled(false);

	
	qlineedit_ip->installEventFilter(im);
	qlineedit_mask->installEventFilter(im);
	qlineedit_gw->installEventFilter(im);
	qlineedit_dns->installEventFilter(im);
	qlineedit_mac->installEventFilter(im);

	qlineedit_ip->setObjectName("qlineedit_ip");
	qlineedit_mask->setObjectName("qlineedit_mask");
	qlineedit_gw->setObjectName("qlineedit_gw");
	qlineedit_dns->setObjectName("qlineedit_dns");
	qlineedit_mac->setObjectName("qlineedit_mac");

    

	QGridLayout *tmpLayout = new QGridLayout(this);

	tmpLayout->addWidget(pipLabel1, 	0,0,1,1);
	tmpLayout->addWidget(pSonnetLabel, 	1,0,1,1);
	tmpLayout->addWidget(ppassnetLabel, 2,0,1,1);
	tmpLayout->addWidget(maclabel, 		3,0,1,1);
	tmpLayout->addWidget(pDNS, 			4,0,1,1);

	tmpLayout->addWidget(qlineedit_ip, 		0,1,1,3);
	tmpLayout->addWidget(qlineedit_mask, 	1,1,1,3);
	tmpLayout->addWidget(qlineedit_gw, 		2,1,1,3);
	tmpLayout->addWidget(qlineedit_mac, 	3,1,1,3);
	tmpLayout->addWidget(qlineedit_dns, 	4,1,1,3);
	
    pipLabel1->setText(    tr("当前IP:  "));
    pSonnetLabel->setText( tr("子网掩码:"));
    ppassnetLabel->setText(tr("默认网关:"));
	maclabel->setText(     tr("MAC地址:"));
    pDNS->setText(         tr("DNS地址:"));


    pSaveButton->setText(tr("保存设置"));
    prefreshButton->setText(tr("刷新"));
	recoverButton->setText(tr("恢复默认设置"));


	qlineedit_ip->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	qlineedit_mask->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	qlineedit_gw->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	qlineedit_dns->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	qlineedit_mac->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

	
	butly->addWidget(mode);
	butly->addWidget(pSaveButton);
	butly->addWidget(prefreshButton);
	butly->addWidget(recoverButton);


    
	pSubLayout->addLayout(tmpLayout, 		0,0,5,4);
	pSubLayout->addLayout(butly, 			5,0,1,4);



    pSubLayout->setMargin(20);
    pSubLayout->setSpacing(10);

    QFrame *pFrame = new QFrame;
    pFrame->setLayout(pSubLayout);

    QGridLayout *pMainLayout = new QGridLayout;
    pMainLayout->addWidget(pFrame, 0, 0, 1, 1);
    pMainLayout->setContentsMargins(40, 15, 40, 15);

	connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));//connect the input method
	connect(process,	SIGNAL(readyRead()),	this,	SLOT(readOut()));
	connect(process1,	SIGNAL(readyRead()),	this,	SLOT(readOut1()));
	

	connect(pSaveButton,		SIGNAL(clicked()), this, SLOT(saveChange()));
	connect(prefreshButton,		SIGNAL(clicked()), this, SLOT(refreshAll()));
	connect(recoverButton,		SIGNAL(clicked()), this, SLOT(recoverToMay()));
	connect(mode, SIGNAL(currentIndexChanged(int)), this, SLOT(modeChanged()));


	
	refreshAll();

	


    pFrame->setObjectName("netSettingsFrame");
    this->setJLayout(pMainLayout);
    this->setJTitle(tr("网络设置"));

}

NetSettings::~NetSettings()
{
	
}


void NetSettings::checkMode()
{
	QFile tmp("/etc/net.sh");

	if (tmp.open(QFile::ReadOnly | QIODevice::Text))
    {
		if(tmp.readAll().contains("udhcpc"))
		{
			qDebug("have udhcpc");
			mode->setCurrentIndex(0);
		}else{		
			qDebug("no udhcpc");
			mode->setCurrentIndex(1);
		}

    }
    
    tmp.close();
}

void NetSettings::modeChanged()
{
	system("killall -9 udhcpc &");


	switch(mode->currentIndex())
	{
		case 0:
			qDebug("动态IP模式");
			system("sh -c udhcpc -b -i eth0 -p /var/run/udhcpd.pid -R &");
			system("echo 'udhcpc -b -i eth0 -p /var/run/udhcpd.pid -R &' > /etc/net.sh &");

			process2->start("sync");
			process2->waitForFinished();

			qlineedit_ip->setEnabled(false);
			qlineedit_gw->setEnabled(false);
			qlineedit_mask->setEnabled(false);

			break;
		case 1:
	
			qDebug("静态IP模式");
			
			qlineedit_ip->setEnabled(true);
			qlineedit_gw->setEnabled(true);
			qlineedit_mask->setEnabled(true);

			break;
	}

	saveChange();

}



void NetSettings::createImConnect(QString ObjName)
{
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_ip,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_mask,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_gw,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_dns,SLOT(setText(QString)));
	disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_mac,SLOT(setText(QString)));


	if(mode->currentIndex() == 1)
	{
    	if(ObjName=="qlineedit_ip")
        	connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_ip,SLOT(setText(QString)));
	    if(ObjName=="qlineedit_mask")
	        connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_mask,SLOT(setText(QString)));
	    if(ObjName=="qlineedit_gw")
	        connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_gw,SLOT(setText(QString)));
	}


        
    if(ObjName=="qlineedit_dns")
        connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_dns,SLOT(setText(QString)));
	if(ObjName=="qlineedit_mac")
        connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_mac,SLOT(setText(QString)));
}

void NetSettings::saveChange()
{
	qDebug("save change");

	system("chmod 777 /etc/net.sh &");
	system(QString("echo '%1' > %2 &").arg(SHELL).arg(NET_SH).toLocal8Bit().data());

	switch(mode->currentIndex())
	{
		case 0:
			system("echo 'udhcpc -b -i eth0 -p /var/run/udhcpd.pid -R &' > /etc/net.sh &");
			break;
		case 1:
			if(IsIPaddress(qlineedit_ip->text())){
				qDebug("it's ipaddr");

				ipCmd = QString("ifconfig eth0 		   %1 &").arg(qlineedit_ip->text());
				system(ipCmd.toLocal8Bit().data());
				system(QString("echo '%1' > %2 &").arg(SHELL).arg(NET_SH).toLocal8Bit().data());
				system(QString("echo '%1' >> %2 &").arg(ipCmd).arg(NET_SH).toLocal8Bit().data());
			}
			
			if(IsIPaddress(qlineedit_mask->text())){
				qDebug("it's mask");
			
				maskCmd = QString("ifconfig eth0 netmask  %1 &").arg(qlineedit_mask->text());
				system(maskCmd.toLocal8Bit().data());
				system(QString("echo '%1' >> %2 &").arg(maskCmd).arg(NET_SH).toLocal8Bit().data());
			}

			if(IsIPaddress(qlineedit_gw->text())){
				qDebug("it's gateway");
			
				gwCmd = QString("route add default gw %1   &").arg(qlineedit_gw->text());
				system(gwCmd.toLocal8Bit().data());
				system(QString("echo '%1' >> %2 &").arg(gwCmd).arg(NET_SH).toLocal8Bit().data());
			}

			break;

	}




	if(IsMACaddress(qlineedit_mac->text())){
		qDebug("it's macaddr");

		hwCmd = QString("ifconfig eth0 hw ether %1 ").arg(qlineedit_mac->text());
		system(hwCmd.toLocal8Bit().data());
		system(QString("echo '%1' >> %2 &").arg(hwCmd).arg(NET_SH).toLocal8Bit().data());
	}

	if(IsIPaddress(qlineedit_dns->text())){
		qDebug("it's dns");

		system(QString("echo 'nameserver %1' > /etc/resolv.conf   &").arg(qlineedit_dns->text()).toLocal8Bit().data());
	}


	{
		QDialog *setdialog = new QDialog;
		QLabel * settmp = new QLabel;
		settmp->setText(tr("保存成功"));
		settmp->setStyleSheet("color:green;");
		QTimer*timer = new QTimer(setdialog);
		timer->start(1500);
		connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
		QGridLayout *tmplayout = new QGridLayout;
		tmplayout->addWidget(settmp,0,0,1,1);
		setdialog->setLayout(tmplayout);
		setdialog->setWindowFlags(Qt::FramelessWindowHint);
		setdialog->exec();
	 
	}

	process2->start("sync");
	process2->waitForFinished();



}


void NetSettings::readOut1()
{
	
	ethInfo = QString(process1->readLine());
//	qDebug() << ethInfo;
	ethInfo.replace(QString(" "), QString(""));
	qlineedit_dns->setText(ethInfo.replace(QString("Server:"), QString("")));



}



void NetSettings::readOut()
{

	char gateway[32] = { 0 };  

	ethInfo = QString(process->readLine());
	ethInfo.replace(QString(" "), QString(""));


//	qDebug() << ethInfo;

	qlineedit_mac->setText(ethInfo.right(18));

	ipInfo = QString(process->readLine()).trimmed().split(" ");
//	qDebug() << ipInfo;

	qlineedit_ip->setText(ipInfo[1].replace(QString("addr:"), QString("")));
	qlineedit_mask->setText(ipInfo[5].replace(QString("Mask:"), QString("")));



	if(GetIPV4Gateway("eth0", gateway, 32) == true)
	{
		qlineedit_gw->setText(QString(gateway));
	}



	
}


void NetSettings::refreshAll()
{
	qlineedit_dns->clear();
	qlineedit_gw->clear();
	qlineedit_ip->clear();
	qlineedit_mac->clear();
	qlineedit_mask->clear();

	qlineedit_dns->setText("DNS地址获取中...");


	process->start("ifconfig eth0");
	process1->start("nslookup eth0");   //use nslookup will waste a lot of times when use dip




}
void NetSettings::getDip()
{
	system("killall -9 udhcpc");
//	system("echo '' > /etc/resolv.conf &");
	sleep(1);
	system("udhcpc -b -i eth0 -p /var/run/udhcpd.pid -R &");
	system("echo 'udhcpc -b -i eth0 -p /var/run/udhcpd.pid -R &' > /etc/net.sh");

	process2->start("sync");
	process2->waitForFinished();

	refreshAll();


}
void NetSettings::recoverToMay()
{
    QString macInfo;
    process_mac->start("/etc/get_org_mac.sh");
    if (process_mac->waitForStarted(-1)) {
    while(process_mac->waitForReadyRead(-1)) {
            macInfo = QString(process_mac->readAllStandardOutput());
            //qDebug() <<"qt get mac :" << macInfo;
        }
    }

	qlineedit_dns->setText("8.8.8.8");
	qlineedit_gw->setText("192.168.1.1");
    qlineedit_ip->setText("192.168.1.16");
    qlineedit_mac->setText(macInfo);
	qlineedit_mask->setText("255.255.255.0");
}


